// 性能优化后的标签页状态管理
// 展示如何应用新的性能优化架构
import {
  BaseStore,
  createBaseState,
  createBaseActions,
  createStore,
  withPerformanceTracking,
  performanceMonitor,
  BatchUpdater
} from '@codegraph/editor-core';
import { TabStatus, Tab, TabGroup, TabHistory, TabConfig } from './tabStore';

/**
 * 优化后的标签页状态接口
 */
export interface OptimizedTabState {
  // 核心状态 - 使用Map提高查找性能
  tabs: Map<string, Tab>;
  tabOrder: string[];
  activeTabId: string | null;
  groups: Map<string, TabGroup>;
  activeGroupId: string | null;
  history: TabHistory;
  config: TabConfig;
  
  // UI状态 - 分离以减少不必要的更新
  uiState: {
    draggedTabId: string | null;
    dropTargetIndex: number | null;
    searchQuery: string;
    filteredTabs: string[];
    isContextMenuOpen: boolean;
    contextMenuPosition: { x: number; y: number } | null;
  };
  
  // 性能统计
  performance: {
    totalTabs: number;
    activeTabs: number;
    memoryUsage: number;
    lastOptimization: number;
    renderCount: number;
  };
}

/**
 * 优化后的标签页操作接口
 */
export interface OptimizedTabActions {
  // 基础操作 - 添加性能跟踪
  openTab: (filePath: string, content?: string) => Promise<string>;
  closeTab: (tabId: string) => void;
  closeAllTabs: () => void;
  closeOtherTabs: (tabId: string) => void;
  setActiveEditor: (tabId: string) => void;
  
  // 批量操作
  batchUpdateTabs: (updates: Array<{ tabId: string; updates: Partial<Tab> }>) => void;
  batchCloseTabs: (tabIds: string[]) => void;
  
  // 性能优化操作
  optimizeMemory: () => void;
  preloadTab: (tabId: string) => Promise<void>;
  unloadInactiveTabs: () => void;
  
  // UI状态操作 - 使用防抖
  setSearchQuery: (query: string) => void;
  setDragState: (draggedTabId: string | null, dropTargetIndex: number | null) => void;
  showContextMenu: (position: { x: number; y: number }) => void;
  hideContextMenu: () => void;
  
  // 选择器优化
  getTabById: (tabId: string) => Tab | undefined;
  getActiveTab: () => Tab | undefined;
  getTabsByGroup: (groupId: string) => Tab[];
  getFilteredTabs: () => Tab[];
  
  // 性能监控
  getPerformanceStats: () => OptimizedTabState['performance'];
  resetPerformanceStats: () => void;
}

/**
 * 完整的优化标签页Store类型
 */
export type OptimizedTabStore = BaseStore<OptimizedTabState & OptimizedTabActions>;

/**
 * 默认配置
 */
const defaultConfig: TabConfig = {
  maxTabs: 20,
  autoSaveInterval: 30000,
  enableAutoSave: true,
  enablePreview: true,
  showCloseButton: true,
  showModifiedIndicator: true,
  tabWidth: 'auto',
  fixedTabWidth: 200,
};

const defaultHistory: TabHistory = {
  recentTabs: [],
  closedTabs: [],
  maxRecentTabs: 10,
  maxClosedTabs: 5,
};

/**
 * 创建优化后的标签页Store
 */
export const useOptimizedTabStore = createStore<OptimizedTabState & OptimizedTabActions>(
  (set, get) => {
    // 创建批量更新器
    const batchUpdater = new BatchUpdater<OptimizedTabState>(
      (updates) => set({ ...updates, lastUpdated: Date.now() }),
      16 // 16ms批量延迟，对应60fps
    );

    // 创建UI状态批量更新器（更长延迟）
    const uiBatchUpdater = new BatchUpdater<OptimizedTabState['uiState']>(
      (updates) => {
        const state = get();
        set({ 
          uiState: { ...state.uiState, ...updates },
          lastUpdated: Date.now()
        });
      },
      100 // 100ms延迟，UI更新不需要太频繁
    );

    // 性能优化的set函数
    const performanceSet = withPerformanceTracking(
      (updates: Partial<OptimizedTabState>) => {
        const state = get();
        set({ 
          ...updates, 
          lastUpdated: Date.now(),
          performance: {
            ...state.performance,
            renderCount: state.performance.renderCount + 1,
          }
        });
      },
      ['tab']
    );

    // 防抖搜索函数
    let searchTimeout: NodeJS.Timeout;
    const debouncedSearch = (query: string) => {
      clearTimeout(searchTimeout);
      searchTimeout = setTimeout(() => {
        const state = get();
        const filteredTabs = query 
          ? Array.from(state.tabs.values())
              .filter(tab => 
                (tab.title || tab.fileName).toLowerCase().includes(query.toLowerCase()) ||
                tab.filePath.toLowerCase().includes(query.toLowerCase())
              )
              .map(tab => tab.id)
          : [];
        
        uiBatchUpdater.add({
          searchQuery: query,
          filteredTabs,
        });
      }, 300);
    };

    return {
      // 基础状态
      ...createBaseState(),
      
      // 标签页特定状态
      tabs: new Map(),
      tabOrder: [],
      activeTabId: null,
      groups: new Map(),
      activeGroupId: null,
      history: { ...defaultHistory },
      config: { ...defaultConfig },
      
      // UI状态
      uiState: {
        draggedTabId: null,
        dropTargetIndex: null,
        searchQuery: '',
        filteredTabs: [],
        isContextMenuOpen: false,
        contextMenuPosition: null,
      },
      
      // 性能统计
      performance: {
        totalTabs: 0,
        activeTabs: 0,
        memoryUsage: 0,
        lastOptimization: Date.now(),
        renderCount: 0,
      },

      // 基础操作
      ...createBaseActions(set, get),

      // 标签页操作
      openTab: async (filePath: string, content: string = '') => {
        const state = get();
        const startTime = performance.now();
        
        // 检查是否已存在
        const existingTab = Array.from(state.tabs.values())
          .find(tab => tab.filePath === filePath);
        
        if (existingTab) {
          performanceSet({ activeTabId: existingTab.id });
          return existingTab.id;
        }

        // 检查标签页数量限制
        if (state.tabs.size >= state.config.maxTabs) {
          // 关闭最旧的非活动标签页
          const oldestTab = Array.from(state.tabs.values())
            .filter(tab => tab.id !== state.activeTabId && !tab.isDirty)
            .sort((a, b) => (a.lastAccessed || 0) - (b.lastAccessed || 0))[0];
          
          if (oldestTab) {
            get().closeTab(oldestTab.id);
          }
        }

        const tabId = `tab_${Date.now()}_${Math.random().toString(36).substring(2, 11)}`;
        const newTab: Tab = {
          id: tabId,
          title: filePath.split('/').pop() || 'Untitled',
          filePath,
          fileName: filePath.split('/').pop() || 'Untitled',
          content,
          originalContent: content,
          isDirty: false,
          status: TabStatus.Clean,
          language: getLanguageFromPath(filePath),
          encoding: 'utf-8',
          lineEnding: '\n',
          cursorPosition: { line: 1, column: 1 },
          scrollPosition: { top: 0, left: 0 },
          isTemporary: false,
          lastAccessed: Date.now(),
          lastModified: Date.now(),
          createdAt: Date.now(),
          groupId: undefined,
        };

        const newTabs = new Map(state.tabs);
        newTabs.set(tabId, newTab);

        const newTabOrder = [...state.tabOrder, tabId];
        
        // 更新历史记录
        const newHistory = {
          ...state.history,
          recentTabs: [tabId, ...state.history.recentTabs.filter(id => id !== tabId)]
            .slice(0, state.history.maxRecentTabs),
        };

        performanceSet({
          tabs: newTabs,
          tabOrder: newTabOrder,
          activeTabId: tabId,
          history: newHistory,
          performance: {
            ...state.performance,
            totalTabs: newTabs.size,
            activeTabs: state.performance.activeTabs + 1,
          },
        });

        // 记录性能
        performanceMonitor.recordUpdate(['openTab'], startTime);
        
        return tabId;
      },

      closeTab: (tabId: string) => {
        const state = get();
        const tab = state.tabs.get(tabId);
        
        if (!tab) return;

        const newTabs = new Map(state.tabs);
        newTabs.delete(tabId);
        
        const newTabOrder = state.tabOrder.filter(id => id !== tabId);
        
        // 更新活动标签页
        let newActiveTabId = state.activeTabId;
        if (state.activeTabId === tabId) {
          const currentIndex = state.tabOrder.indexOf(tabId);
          if (newTabOrder.length > 0) {
            const nextIndex = Math.min(currentIndex, newTabOrder.length - 1);
            newActiveTabId = newTabOrder[nextIndex];
          } else {
            newActiveTabId = null;
          }
        }

        // 添加到关闭历史
        const newHistory = {
          ...state.history,
          closedTabs: [tab, ...state.history.closedTabs]
            .slice(0, state.history.maxClosedTabs),
          recentTabs: state.history.recentTabs.filter(id => id !== tabId),
        };

        performanceSet({
          tabs: newTabs,
          tabOrder: newTabOrder,
          activeTabId: newActiveTabId,
          history: newHistory,
          performance: {
            ...state.performance,
            totalTabs: newTabs.size,
            activeTabs: Math.max(0, state.performance.activeTabs - 1),
          },
        });
      },

      closeAllTabs: () => {
        const state = get();
        const dirtyTabs = Array.from(state.tabs.values()).filter(tab => tab.isDirty);
        
        if (dirtyTabs.length > 0) {
          // 这里应该显示确认对话框，暂时跳过脏标签页
          const cleanTabs = Array.from(state.tabs.values()).filter(tab => !tab.isDirty);
          cleanTabs.forEach(tab => get().closeTab(tab.id));
        } else {
          performanceSet({
            tabs: new Map(),
            tabOrder: [],
            activeTabId: null,
            performance: {
              ...state.performance,
              totalTabs: 0,
              activeTabs: 0,
            },
          });
        }
      },

      closeOtherTabs: (keepTabId: string) => {
        const state = get();
        const tabsToClose = Array.from(state.tabs.keys()).filter(id => id !== keepTabId);
        get().batchCloseTabs(tabsToClose);
      },

      batchUpdateTabs: (updates: Array<{ tabId: string; updates: Partial<Tab> }>) => {
        const state = get();
        const newTabs = new Map(state.tabs);
        
        updates.forEach(({ tabId, updates: tabUpdates }) => {
          const existingTab = newTabs.get(tabId);
          if (existingTab) {
            newTabs.set(tabId, { ...existingTab, ...tabUpdates });
          }
        });

        batchUpdater.add({ tabs: newTabs });
      },

      batchCloseTabs: (tabIds: string[]) => {
        tabIds.forEach(tabId => get().closeTab(tabId));
      },

      optimizeMemory: () => {
        const state = get();
        const now = Date.now();
        const maxAge = 30 * 60 * 1000; // 30分钟
        
        const newTabs = new Map(state.tabs);
        let optimized = 0;
        
        for (const [id, tab] of newTabs) {
          // 清理长时间未访问的标签页内容
          if (
            id !== state.activeTabId && 
            !tab.isDirty && 
            now - (tab.lastAccessed || 0) > maxAge
          ) {
            newTabs.set(id, { ...tab, content: '' }); // 清空内容，保留元数据
            optimized++;
          }
        }

        if (optimized > 0) {
          performanceSet({
            tabs: newTabs,
            performance: {
              ...state.performance,
              lastOptimization: now,
              memoryUsage: state.performance.memoryUsage * 0.8, // 估算内存减少
            },
          });
          
          console.log(`Optimized ${optimized} tabs, estimated memory reduction: 20%`);
        }
      },

      preloadTab: async (tabId: string) => {
        const state = get();
        const tab = state.tabs.get(tabId);
        
        if (tab && !tab.content) {
          // 这里应该从文件系统加载内容
          // 暂时模拟异步加载
          setTimeout(() => {
            const currentState = get();
            const currentTab = currentState.tabs.get(tabId);
            if (currentTab) {
              const newTabs = new Map(currentState.tabs);
              newTabs.set(tabId, { 
                ...currentTab, 
                content: `// Content for ${tab.filePath}` 
              });
              batchUpdater.add({ tabs: newTabs });
            }
          }, 100);
        }
      },

      unloadInactiveTabs: () => {
        const state = get();
        const inactiveThreshold = 10 * 60 * 1000; // 10分钟
        const now = Date.now();
        
        const newTabs = new Map(state.tabs);
        let unloaded = 0;
        
        for (const [id, tab] of newTabs) {
          if (
            id !== state.activeTabId && 
            !tab.isDirty && 
            now - (tab.lastAccessed || 0) > inactiveThreshold &&
            tab.content
          ) {
            newTabs.set(id, { ...tab, content: '' });
            unloaded++;
          }
        }

        if (unloaded > 0) {
          batchUpdater.add({ tabs: newTabs });
          console.log(`Unloaded ${unloaded} inactive tabs`);
        }
      },

      // UI状态操作
      setSearchQuery: (query: string) => {
        debouncedSearch(query);
      },

      setDragState: (draggedTabId: string | null, dropTargetIndex: number | null) => {
        uiBatchUpdater.add({
          draggedTabId,
          dropTargetIndex,
        });
      },

      showContextMenu: (position: { x: number; y: number }) => {
        uiBatchUpdater.add({
          isContextMenuOpen: true,
          contextMenuPosition: position,
        });
      },

      hideContextMenu: () => {
        uiBatchUpdater.add({
          isContextMenuOpen: false,
          contextMenuPosition: null,
        });
      },

      // 选择器优化
      getTabById: (tabId: string) => {
        return get().tabs.get(tabId);
      },

      getActiveTab: () => {
        const state = get();
        return state.activeTabId ? state.tabs.get(state.activeTabId) : undefined;
      },

      getTabsByGroup: (groupId: string) => {
        const state = get();
        return Array.from(state.tabs.values()).filter(tab => tab.groupId === groupId);
      },

      getFilteredTabs: () => {
        const state = get();
        if (!state.uiState.searchQuery) {
          return Array.from(state.tabs.values());
        }
        return state.uiState.filteredTabs
          .map(id => state.tabs.get(id))
          .filter(Boolean) as Tab[];
      },

      // 设置活动编辑器
      setActiveEditor: (tabId: string) => {
        const state = get();
        if (state.tabs.has(tabId)) {
          set({ activeTabId: tabId });
          // 更新最后访问时间
          const tab = state.tabs.get(tabId);
          if (tab) {
            const updatedTab = { ...tab, lastAccessed: Date.now() };
            const newTabs = new Map(state.tabs);
            newTabs.set(tabId, updatedTab);
            set({ tabs: newTabs });
          }
        }
      },

      // 性能监控
      getPerformanceStats: () => {
        return get().performance;
      },

      resetPerformanceStats: () => {
        const state = get();
        performanceSet({
          performance: {
            ...state.performance,
            renderCount: 0,
            lastOptimization: Date.now(),
          },
        });
      },
    };
  },
  {
    name: 'optimized-tab',
    enablePersist: true,
    version: 1,
    enableDevtools: true,
    enableSubscribeWithSelector: true,
  }
);

/**
 * 根据文件路径获取语言类型
 */
function getLanguageFromPath(filePath: string): string {
  const ext = filePath.split('.').pop()?.toLowerCase();
  const languageMap: Record<string, string> = {
    'ts': 'typescript',
    'tsx': 'typescript',
    'js': 'javascript',
    'jsx': 'javascript',
    'py': 'python',
    'rs': 'rust',
    'go': 'go',
    'java': 'java',
    'cpp': 'cpp',
    'c': 'c',
    'h': 'c',
    'hpp': 'cpp',
    'css': 'css',
    'scss': 'scss',
    'html': 'html',
    'xml': 'xml',
    'json': 'json',
    'md': 'markdown',
    'yml': 'yaml',
    'yaml': 'yaml',
  };
  
  return languageMap[ext || ''] || 'plaintext';
}
